package cn.david.org.service.impl;

import cn.david.basic.util.PageList;
import cn.david.org.domain.Department;
import cn.david.org.mapper.DepartmentMapper;
import cn.david.org.query.DepartmentQuery;
import cn.david.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl implements IDepartmentService {
    @Autowired
    DepartmentMapper departmentMapper;
    @Override
    public void add(Department department) {
        departmentMapper.save(department);
        //给dirPath处理  -- /父级部门/父级部门/自己的id
        /*
            1.如果没有传上级部门  dirPath /自己的id
            2.如果传了上级部门
                11-->    /1/11/id
               查询id为11 数据   找到 dirPath + /自己的id
               1-->     /1/id
         */
        //没有选择上级部门的情况
        if (department.getParent()==null ||department.getParent().getId()==null){
            department.setDirPath("/"+department.getId());
        }else {
            Department dept = departmentMapper.loadById(department.getParent().getId());
            department.setDirPath(dept.getDirPath()+"/"+department.getId());
        }
        departmentMapper.update(department);

    }

    @Override
    public void update(Department department) {
        //没有选择上级部门的情况
        if (department.getParent()==null ||department.getParent().getId()==null){
            department.setDirPath("/"+department.getId());
        }else {
            //获取上级部门的dirpath
            Department dept = departmentMapper.loadById(department.getParent().getId());
            department.setDirPath(dept.getDirPath()+"/"+department.getId());
        }
        departmentMapper.update(department);


    }

    @Override
    public void delete(Long id) {
        departmentMapper.remove(id);

    }

    @Override
    public Department queryById(Long id) {
        return departmentMapper.loadById(id);
    }

    @Override
    public List<Department> queryAll() {
        return departmentMapper.loadAll();
    }

    @Override
    public PageList<Department> queryPage(DepartmentQuery query) {
        Integer total = departmentMapper.queryCount(query);
        List<Department> data = departmentMapper.queryData(query);
        return new PageList<Department>(total,data);
    }

    @Override
    public void deleteByIds(Long[] ids) {
        departmentMapper.deleteByIds(ids);

    }

    @Override
    public List<Department> getDeptTree() {
        return departmentMapper.getDeptTree();
    }
}
